package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMateriaMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Autowired
    private WmNewsMateriaMapper wmNewsMateriaMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;


    //引入自动审核业务的接口
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 延迟化
     */
    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    //kafuka的模板类
    @Autowired
    private KafkaTemplate <String, String> kafkaTemplate;




    /**
     * 文章列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //执行分页

        IPage<WmNews> ipage = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();
        page(ipage, queryWrapper);
        //条件过滤
        //状态
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());//不为空 将状态传回去
        }
        //时间
        if (dto.getBeginPubdate() != null && dto.getBeginPubdate() != null) {
            queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }
        //关键字
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            queryWrapper.eq(WmNews::getTitle, dto.getKeyword());
        }
        //频道
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //当前用户
        queryWrapper.eq(WmNews::getUserId, WmThreadLocal.getWmUser().getId());

        //封装数据
        ResponseResult result = new PageResponseResult(dto.getSize(), dto.getPage(), (int) ipage.getTotal());
        //结果集
        result.setData(ipage.getRecords());
        return result;
    }

    /**
     * 文章发布  保存草稿 修改 三合一
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //1、参数校验
        if (dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //自动
        if (dto.getType() == -1) {
            dto.setType(null);
        }
        //2.修改和保存的方法
        WmNews wmnews = new WmNews();
        BeanUtils.copyProperties(dto, wmnews);
        //封装数据userid
        wmnews.setUserId(WmThreadLocal.getWmUser().getId());
        wmnews.setCreatedTime(new Date());
        //解决格式
        List<String> images = dto.getImages();
        if (images.size() > 0 && images != null) {
            String image = org.apache.commons.lang3.StringUtils.join(images, ",");
            wmnews.setImages(image);
        }
        saveOrUpdateWnews(wmnews);
        //3. 判断是否为草稿，如果为草稿，则以下步骤不再执行
        if (dto.getStatus() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CAOGAO_EXIST);
        }
        //3.5 把内容中content里面的图片给抽取出来
        List<String> imageList = chouquImageList(wmnews);

        //4.关联内容中的图片与文章的关系，操作wm_news_marterial表，批量新增中间表
        //4.2 要把图片地址集合转化成地址所对应的素材id,根据图片地址去查询wm_material表从而获取对应的素材id
        contentImageToNews(wmnews, imageList, 0);

        //5.关联封面中的图片与文章的关系，操作wm_news_marterial表
        //5.1 判断封面是否是自动
        //返回值一定此时是空的
        fengmianImageToNews(dto, wmnews, imageList);
        //6.执行异步调用自动审核业务

//        wmNewsAutoScanService.autoScanWmNews(wmnews.getId());
        wmNewsTaskService.addNewsToTask(wmnews.getId(),wmnews.getPublishTime());
        return ResponseResult.okResult("发布成功");

    }

    /**
     * 封面图片与文章的关系
     *
     * @param dto
     * @param wmnews
     * @param imageList
     */
    private void fengmianImageToNews(WmNewsDto dto, WmNews wmnews, List<String> imageList) {
        List<String> fengminaImages = dto.getImages();
        if (dto.getType() == null) {

            //内容中的图片个数大于等于1小于3，此时我们认为是单图
            if (imageList.size() >= 1 && imageList.size() < 3) {
                fengminaImages = imageList.stream().limit(1).collect(Collectors.toList());
                wmnews.setType((short) 1);
            } else if (imageList.size() >= 3) {//多图
                fengminaImages = imageList.stream().limit(3).collect(Collectors.toList());
                wmnews.setType((short) 3);
            } else {//内容中也没有图片，我们认为无图
                wmnews.setType((short) 0);
            }
            wmnews.setImages(org.apache.commons.lang.StringUtils.join(fengminaImages, ","));
            updateById(wmnews);
        }
        //批量新增中间表
        contentImageToNews(wmnews, fengminaImages, 1);
    }

    /**
     * 抽取的方法三，内容图片与文章的关系
     *
     * @param wmnews
     * @param imageList
     * @param type
     */
    private void contentImageToNews(WmNews wmnews, List<String> imageList, Integer type) {
        if (imageList.size() > 0 && imageList != null) {
            //根据图片地址集合获取素材集合
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageList));
            //stream流获取素材id集合
            List<Integer> materialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //4.1 调用mapper接口
            wmNewsMateriaMapper.saveBatch(materialIds, wmnews.getId(), type);
        }
    }

    /**
     * 抽取的第二个方法，获取文本内容中的图片地址集合
     *
     * @param wmnews
     * @return
     */
    private List chouquImageList(WmNews wmnews) {
        List<String> imageUrlList = new ArrayList<>();


        //1.获取内容
        String content = wmnews.getContent();
        //2.转化类型格式，list嵌套map格式
        List<Map> mapList = JSON.parseArray(content, Map.class);
        //3.从map中获取type=image的value值
        for (Map map : mapList) {
            if (map.get("type").equals("image")) {//就是图片
                String imageUrl = (String) map.get("value");
                imageUrlList.add(imageUrl);
            }
        }
        return imageUrlList;

    }

    /**
     * 抽取的第一个方法，修改和保存文章
     */
    private void saveOrUpdateWnews(WmNews wmNews) {
        //修改
        if (wmNews.getId() != null) {
            //删除中间表
            wmNewsMateriaMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //修改文章表
            updateById(wmNews);
        } else {
            //新增
            save(wmNews);
        }
    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ////2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.判断文章是否已发布
        if (wmNews.getStatus()!=WmNews.Status.PUBLISHED.getCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章enable
        wmNews.setEnable(dto.getEnable());
        boolean flag = updateById(wmNews);
        if (!flag){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"修改状态失败");
        }

        //发送内容
        if (wmNews.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"ID不能为空");
        }
        Map map=new HashMap();
        map.put("articleId",wmNews.getArticleId());
        map.put("enable",wmNews.getEnable());
        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        ///返回数据
        return ResponseResult.okResult("修改成功");
    }
}
